const jwt = require('jsonwebtoken');
const md5 = require('md5');
let path = require('path');
let multer = require('multer');

// 格式化响应数据
module.exports.formatResponse = function (code, msg, data) {
  return {
    code,
    msg,
    data
  }
}

// 验证token
module.exports.tokenMiddleWare = function (token) {
  return jwt.verify(token.split(' ')[1], md5(process.env.JWT_SECRET))
}

function randomName() {
  const date = new Date();
  return `${date.getFullYear()}-${date.getMonth() + 1
    }-${date.getDate()}-${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}-${date.getMilliseconds()}-${Math.random()
      .toString(16)
      .substr(2, 5)}`;
}

// 设置上传文件的引擎
const storage = multer.diskStorage({
  // 设置上传文件的目录
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, '../public/static/uploads'))
  },
  // 设置上传文件的文件名
  filename: function (req, file, cb) {
    const baseName = path.basename(file.originalname, path.extname(file.originalname))
    const extName = path.extname(file.originalname)
    const fileName = baseName + '-' + randomName() + extName
    cb(null, fileName)
  }
})

module.exports.uploading = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 2,
    files: 1
  }
})